let cfg = {};
cfg.root_url = "http://localhost:8080";
cfg.repos = cfg.root_url + "/flashSale/repos"; // get库存
cfg.purchase = cfg.root_url + "/flashSale/purchase"; // post抢购
cfg.orders = cfg.root_url + "/order"; // 订单列表
cfg.pay = cfg.root_url + "/pay/pay"; // post支付
function dateFormat1(fmt, date) {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
}
function dateFormat(date) {
    return dateFormat1("YYYY-mm-dd HH:MM", date);
}

global_data = {

}

// data convert
let ORDER_STATUS_MAP = {not_pay: '待支付', payed: '已支付', timeout: '超时', low_stocks: '库存不足'}
function dataConvert(data) {
    let converted = data;
    if (converted.orderStatus) converted.status = ORDER_STATUS_MAP[converted.orderStatus];
    if (converted.createTime) converted.createTime = dateFormat(new Date(converted.createTime));
    if (converted.payTime) converted.payTime = dateFormat(new Date(converted.payTime));

    return converted;
}

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == variable){return pair[1];}
    }
    return(false);
}

function countdown(e, n, handle) {
    n = parseInt(n / 1000);

    if (n <= 0) {
        n = 0;
        handle(e, n);
        return;
    }

    handle(e, n);
    let id = setInterval(function () {
        if (n <= 0) {
            n = 0;
            clearInterval(id);
            handle(e, n);
            return;
        }
        n = n - 1;
        handle(e, n);
    }, 1000);
}


// net
function reqErrorHandler(req) {
    console.log(this.responseText);
}
function req(url, method, reqHandler, data) {
    let req = new XMLHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            if (req.status == 200) {
                reqHandler(this);
            } else {
                reqErrorHandler(this);
            }
        }
    }
    req.open(method, url);
    req.setRequestHeader("Content-type","application/json;charset=UTF-8")
    if (data != undefined || data == null) req.send(data);
    else req.send();
}
function get(url, reqListenerLoad) {
    req(url, "GET", reqListenerLoad);
}
function post(url, reqListenerLoad, data) {
    req(url, "POST", reqListenerLoad, data);
}

// handler
function generOrderPayPage(orderId) {
    return 'order-pay.html?orderId=' + orderId;
}

// 获取库存
let tdTemplate =
    '<td>{productId}</td>' +
    '<td>...</td>' +
    '<td>{numbers}</td>' +
    '<td>' +
    '    <button class="btn toPay" onclick="purchase({productId})">抢购</button>' +
    '</td>'
;
function getProductsHandler(req) {
    let data = JSON.parse(req.responseText);

    let tb = document.getElementById('productsList');
    for (i in data) {
        let tds = tdTemplate;
        tds = tds.replace('{productId}', i);
        tds = tds.replace('{numbers}', data[i]);
        tds = tds.replace('{productId}', i); // 设置”抢购“按钮中的参数

        let tr = document.createElement('tr');
        tr.innerHTML = tds;

        tb.appendChild(tr);
    }

    // 更新库存
    global_data['repo'] = data
}
function getProducts() {
    get(cfg.repos, getProductsHandler);
}


function purchaseHandler(req) {
    let orderId = req.responseText;
    location.href = generOrderPayPage(orderId);
}
function purchase(productId) {

    repoNum = global_data['repo'][productId]
    if (repoNum <= 0) {
        alert("库存不足");
        return;
    }

    data = {
        productId: productId,
        numbers: 1
    }
    post(cfg.purchase, purchaseHandler, JSON.stringify(data))
}

// 订单处理
let getOrdersTdTemplate =
    '<td>{orderId}</td>' +
    '<td>{productId}</td>' +
    '<td>...</td>' +
    '<td>{orderStatus}</td>' +
    '<td>{createTime}</td>' +
    '<td>{msg}</td>'
;
function getOrdersHandler(req) {
    let data = JSON.parse(req.responseText);

    let tb = document.getElementById('orderList');
    for (i in data) {
        let d = dataConvert(data[i]);
        let tds = getOrdersTdTemplate;
        tds = tds.replace('{productId}', d.productId);
        tds = tds.replace('{orderId}', d.orderId);
        tds = tds.replace('{orderStatus}', d.orderStatus);
        tds = tds.replace('{createTime}', d.createTime);
        tds = tds.replace('{msg}', d.msg);

        let tr = document.createElement('tr');
        tr.innerHTML = tds;

        tb.appendChild(tr);
    }
}
function getOrders() {
    get(cfg.orders, getOrdersHandler);
}

// 支付
function getOrderDetail() {
    let orderId = getQueryVariable('orderId');
    let e = document.getElementById('orderDetail');
    e.innerHTML = "订单号：" + orderId;

    // countdow
    let countdownShow = document.getElementById("countdownShow");
    if (countdownShow) {
        countdown(countdownShow, 30 * 1000, countdownHandler);
    }
}

function countdownHandler(e, n) {
    e.innerText = n;

    let payBtn = document.getElementById("payBth");
    if (n <= 0) {
        payBtn.setAttribute('disabled', 'disabled');
        payBtn.style = 'background-color: #b8b7b7;';
    } else {
        payBtn.removeAttribute('disabled');
        payBtn.style = 'background-color: #eaeaea;';
    }
}

function payHandler(req) {
    let resp = JSON.parse(req.responseText);
    if (resp != 'payed') {
        let errMsg = document.getElementById('errMsg');
        errMsg.innerText = '支付失败';
        errMsg.removeAttribute('hidden');
    } else {
        location.href = 'order-list.html';
    }
}
function pay() {
    let orderId = getQueryVariable('orderId');
    data = JSON.stringify({
        orderId: orderId,
        paymentAmount: 111
    })
    post(cfg.pay, payHandler, data);
}
